准备动态库
使用Visual Studio 2017创建项目,如图所示,选中动态链接库后点击确定。 创建好的工程如下图所示 添加Dll2.h头文件 并在头文件中输入代码:
#pragma once
#include
/* To use this exported function of dll, include this header
* in your project.
*/
#ifdef BUILD_DLL // 记下这个
#define DLL_EXPORT __declspec(dllexport)
#else
#define DLL_EXPORT __declspec(dllimport)
#endif
#ifdef __cplusplus
extern "C"
{
#endif
unsigned int DLL_EXPORT log2_d(unsigned int n);
long long DLL_EXPORT sum(int x, int y);
DLL_EXPORT char* reverse(char *s);
#ifdef __cplusplus
}
#endif
由于在python中只能调用C,因此需要利用extern C指示编译器将代码按C进行编译。
在Dll2.cpp文件中添加代码如下:
// Dll2.cpp: 定义 DLL 应用程序的导出函数。
#include "stdafx.h"
#define BUILD_DLL //此处需要进行宏定义,名称和头文件中保持一致,且需要在includet头文件之前。
#include "Dll2.h"
#include
unsigned int DLL_EXPORT log2_d(unsigned int n) {
unsigned int result = 0; unsigned int cp = n;
if (n & 0xffff0000) { result += 16; n >>= 16; }
if (n & 0x0000ff00) { result += 8; n >>= 8; }
if (n & 0x000000f0) { result += 4; n >>= 4; }
if (n & 0x0000000c) { result += 2; n >>= 2; }
if (n & 0x00000002) { result += 1; n >>= 1; }
if (cp > 1 |